<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-03-17
 * Time: 15:37
 */

namespace app\src\sunsun\water_pump\action;

use app\src\base\helper\ResultHelper;
use app\src\base\helper\ValidateHelper;
use app\src\sunsun\common\helper\DeviceInfoPollHelper;
use app\src\sunsun\common\logic\UserDeviceLogic;
use app\src\sunsun\water_pump\logic\WaterPumpDeviceLogic;
use sunsun\water_pump\req\WaterPumpDeviceInfoReq;


/**
 * Class WaterPumpDeviceInfoAction
 * 获取设备信息
 * @package app\src\sunsun\water_pump
 */
class WaterPumpDeviceInfoAction extends WaterPumpBaseAction
{
    /**
     * 获取设备信息
     * @param $did
     * @param int $uid
     * @param int $getDeviceInfo
     * @return array
     */
    public function deviceInfo($did, $uid = 0, $getDeviceInfo = 1)
    {
        if (intval($uid) < 0) {
            return ResultHelper::error('该用户不存在');
        }
        if ($uid == 0) {
            $deviceInfo = [];
        } else {
            $result = (new UserDeviceLogic())->getInfo(['uid' => $uid, 'did' => $did]);
            if (!ValidateHelper::legalArrayResult($result)) {
                return ResultHelper::error('该设备信息不存在');
            }
            $deviceInfo = $result['info'];
        }
        $result = (new WaterPumpDeviceLogic())->getInfo(['did' => $did]);
        if (!ValidateHelper::legalArrayResult($result)) {
            return ResultHelper::error('该设备信息不存在');
        }

        $result['info'] = array_merge($this->processDevice($result['info']), $deviceInfo);

        $deviceInfo = $result['info'];

        if ($getDeviceInfo) {
            DeviceInfoPollHelper::poll($deviceInfo, new WaterPumpDeviceInfoReq(), new WaterPumpDeviceLogic());
        }
        return $result;
    }

    private function processDevice($info)
    {
        if (!is_array($info)) {
            return $info;
        }
        $info['is_disconnect'] = 0;
        //如果tcp通道id为空，则设备已断开
        if (empty($info['tcp_client_id'])) {
            $info['is_disconnect'] = 2;
        }
        $info['online_time'] = $info['wh'] * 3600;
        return $info;
    }
}